﻿using HBKY.Shop.Common;
using HBKY.Shop.Common.Helper;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace HBKY.Shop.Common.RabbitMQ.DependencyInjection
{
    public static class RabbitMQServiceCollectionExtensions
    {
        /// <summary>
        /// 依赖注入使用RabbitMQ
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services)
        {
            services.AddTransient<IRabbitMQClient, RabbitMQClient>(x =>
            {
                var configuration = x.GetService<IConfiguration>();
                return new RabbitMQClient(configuration);
            });

            return services;
        }

        /// <summary>
        /// 注册消费端
        /// </summary>
        /// <param name="app"></param>
        /// <param name="serviceProvider"></param>
        public static void RegisterRabbitMQInvoker(this IApplicationBuilder app, IServiceProvider serviceProvider)
        {
            if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));

            if (!Appsettings.Option("RabbitMQ", "SubscribeEnabled").ObjToBool()) return;

            var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes().Where(t => t.BaseType != null &&
                                                     (t.BaseType.Name == typeof(WorkQueuesBase<>).Name
                                                      || t.BaseType.Name == typeof(PublishSubscribeBase<>).Name)
            )).ToArray();
            foreach (var type in types)
            {
                var queue = serviceProvider.GetService(type) as QueueBase;
                queue.Execute();
            }
        }
    }
}